/**
 * Thing对象
 * @author keluo <pycorvn@yeah.net>
 * @since 2012-12-5 17:18:35
 */
var Thing = {
	
	option : {
		host_user_id : null // 该主页用户id
	},
		
	init : function(option) {
		this.option.host_user_id = option.host_user_id;
		var _this = this;
		if($('#things .thing').length == 0) {
			// $.get()...
		} else {
			$('#things .thing').each(function() {
				_this.attach($(this).attr('data-thing-id'));
			});
		}
	},
	
	/**
	 * @param int divide 分隔点thing_id
	 * @param int number 获取thing条数
	 * @param bool later true则获取thing_id大于divide的thing，否则获取小于divide的thing
	 * @param function callback 回调方法名
	 * @return void
	 */
	fetchThings : function(divide, number, later, callback) {
		var _this = this;
		var later = later ? 1 : 0;
		var url = SCABISH.host+'/thing/getThings/host_user_id/'+_this.option.host_user_id;
		url += '/divide/'+divide+'/later/'+later+'/number/'+number;
		$.get(url, function(response) {
			if(SCABISH.isOk(response)) {
				var things = SCABISH.obtain(response);
				for(var i = 0; i < things.length; i++) {
					if(later) {
						$(_this.getTemplate(things[i])).hide().prependTo($('#things')).slideDown();
					} else {
						$(_this.getTemplate(things[i])).hide().appendTo($('#things')).slideDown();
					}
					
					_this.attach(things[i].thing_id);
				}
				if(typeof callback == 'function') callback(things.length);
			} else { // 返回失败代码
				var code = SCABISH.obtain(response);
				if(code == 'user_not_login') { // 未登录
					LOGIN.show(function() {
						if(LOGIN.success) { // 登录成功 
							_this.fetchThings(divide, number, later, callback);
						} else {// 被取消登录
							callback(-1);
						}
					});
				} else { // 其他未知问题
					//SCABISH.error(code)
				}
			}
		});
	},
	
	getTemplate : function(thing) {
		var template = '\
		<div class="thing" data-thing-id="'+thing.thing_id+'" data-thing-type="'+thing.type+'">\
			<div class="timeline" style="visibility:hidden;">\
				<a href="'+SCABISH.host+'/thing/view/thing_id/'+thing.thing_id+'" target="_blank">'+thing.post_date+'</a>\
			</div>\
			<div class="content">'+thing.text+'</div>';
		if(thing.type == 'photo') {
			template += '\
			<div class="photo">\
				<!-- 默认显示中图 -->\
				<div class="medium">\
    				<img src="'+SCABISH.host+'/upload/'+thing.photos[0].thumbs[400]['path']+'" />\
    				<span class="count">'+thing.photos.length+'p</span>\
				</div>\
				<ul class="thumbnail">';
			for(var i = 0; i < thing.photos.length; i++) {
				template += '\
					<li'+(i > 5 ? 'style="display:none;"' : '')+'>\
						<a class="fancybox" rel="group'+thing.thing_id+'" href="'+SCABISH.host+'/upload/'+thing.photos[i].path+'" title="'+thing.text+'" onclick="return false;">\
							<img src="'+SCABISH.host+'/upload/'+thing.photos[i].thumbs[80]['path']+'" />\
						</a>\
					</li>';
			}
			template += '\
				</ul>\
			</div>';
		} else if(thing.type == 'video') {
			template += '\
			<div class="video">\
				<img src="'+SCABISH.host+'/upload/'+thing.video.preview_path+'" width="'+thing.video.preview_width+'" height="'+thing.video.preview_height+'" />\
				<div class="play" data-video-url="'+thing.video.url+'" \
					data-video-width="'+thing.video.width+'" data-video-height="'+thing.video.height+'">\
				</div>\
			</div>\
			<div class="player" style="display:none;"></div>';
		} else if(thing.type == 'music') {
			template += '\
			<div class="music">\
				<img src="'+SCABISH.host+'/upload/'+thing.music.preview_path+'" width="'+thing.music.preview_width+'" height="'+thing.music.preview_height+'" />\
				<div class="play" data-music-url="'+thing.music.url+'" \
					data-music-width="'+thing.music.width+'" data-music-height="'+thing.music.height+'">\
				</div>\
			</div>\
			<div class="player" style="display:none;"></div>';
		}
		template += '\
			<div class="opt clear">\
				<a class="edit" href="javascript:;" style="display:none;"></a>\
				<a class="delete" href="javascript:;" style="display:none;"></a>\
				<a class="echo" href="javascript:;"><span class="echo-num">'+(thing.comment_num == 0 ? '' : thing.comment_num)+'</span></a>\
				<a class="share" href="javascript:;"></a>\
				<a class="mark" href="javascript:;"></a>\
    		</div>\
    		<div class="echoes" style="display:none"></div>\
		</div>';
		
		return template;
	},
	
	// 为指定thing附加事件
	attach : function(thing_id) {
		var $thing = this.getThingObj(thing_id);
		var thing_type = this.getThingType(thing_id);
		this.attachCommon(thing_id);
		switch(thing_type) {
			case 'video':
				this.attachVideo(thing_id);
			break;
			case 'music':
				this.attachMusic(thing_id);
			break;
			case 'photo':
				this.attachPhoto(thing_id);
			break;
		}
	},
	
	// 注册公共事件
	attachCommon : function(thing_id) {
		var _this = this;
		var $thing = this.getThingObj(thing_id);
		$thing.hover(function() {
			$thing.find('.timeline').css('visibility', 'visible');
			if(LOGIN.getUserCacheId() && LOGIN.getUserCacheId() != $(this).attr('data-user-id')) {
				$thing.find('.opt .edit, .opt .delete').show();	
			}
		}, function(){
			$thing.find('.timeline').css('visibility', 'hidden');
			$thing.find('.opt .edit, .opt .delete').hide();
		});
		
		$thing.find('.opt .delete').click(function() {
			$.dialog({
				content : '确认要删掉吗？',
				lock : true,
				width : 200,
				okValue : '是的',
				cancelValue : '哦不',
				ok : function() {
					_deleteThing(thing_id);
				},
				cancel : function() {}
			});
		});
		
		var _deleteThing = function(thing_id) {
			$.post(SCABISH.host+'/thing/delete/thing_id/'+thing_id, function(response) {
				if(SCABISH.isOk(response)) {
					$thing.slideUp($(this).remove());
				} else {
					var code = SCABISH.obtain(response);
					if(code == 'user_not_login') { // 未登录
						LOGIN.show(function() {
							if(LOGIN.success) { // 登录成功
								_deleteThing(thing_id);
							}
						});
					} else if(code == 'user_cannot_access') { // 无操作权限
						$.dialog({
							'content' : '<span style="color:#FF7F24;font-size:14px;">无此操作权限</span>'
						}).time(1000);
					} else { // 其他未知问题
						//SCABISH.error(code)
						//console.log(code)
					}
				}
			});
		};
		
		$thing.find('.opt .echo').click(function() {
			if($thing.find('.echoes').is(':hidden')) {
				new ThingEcho({
					'thing_id':thing_id, 
					'host_user_id' : _this.option.host_user_id, 
					'page_id':1, 'num_per_page':10
				});
			} else {
				$thing.find('.echoes').slideUp(function() {$(this).empty();});
			}
		});
	},
	
	attachVideo : function(thing_id) {
		var $thing = this.getThingObj(thing_id);
		
		var recreate = function() {
			$player = $thing.find('.play');
			return '\
			<div>\
				<embed src="'+$player.attr('data-video-url')+'"\
					type="application/x-shockwave-flash" width="'+$player.attr('data-video-width')+'"\
					height="'+$player.attr('data-video-height')+'" wmode="transparent" play="true"\
					loop="false" menu="false" allowscriptaccess="never">\
				</embed>\
			</div>';
		};
		
		$thing.find('.video .play').click(function() {
			$thing.find('.video img').click();
		});
		
		$thing.find('.video img').hover(function() {
			$(this).stop().animate({'opacity': 0.7});
		}, function() {
			$(this).stop().animate({'opacity': 1});
		}).click(function() {
			var $player = $thing.find('.player');
			if($player.is(':hidden')) {
				$(this).parent().hide();
				var html = recreate();
				html += '<div><a href="javascript:;" class="turnup"></a><a href="javascript:;" class="reload"></a></div>';
				$player.hide().html(html).fadeIn();
			} else {
				var _this = $(this);
				$player.animate({height:0}, 'normal', 'swing', function() {
					$(this).css({'height':''}).empty().hide();
					_this.parent().slideDown();
				});
			}
			
			$player.find('.turnup').die().live('click', function() {
				$thing.find('.video img').click();
			});
			
			$player.find('.reload').die().live('click', function() {
				$player.children().eq(0).fadeOut(function() {
					$(this).remove();
					$player.prepend(recreate());
				})
			});
		});
	},
	
	attachMusic : function(thing_id) {
		var $thing = this.getThingObj(thing_id);
		
		var recreate = function() {
			$player = $thing.find('.play');
			return '\
			<div>\
				<embed src="'+$player.attr('data-music-url')+'"\
					type="application/x-shockwave-flash" width="'+$player.attr('data-music-width')+'"\
					height="'+$player.attr('data-music-height')+'" wmode="transparent" play="true"\
					loop="false" menu="false" allowscriptaccess="never">\
				</embed>\
			</div>';
		};
		
		$thing.find('.music .play').click(function() {
			$thing.find('.music img').click();
		});
		
		$thing.find('.music img').hover(
			function() {
				$(this).stop().animate({'opacity': 0.7});
			}, function() {
				$(this).stop().animate({'opacity': 1});
			}	
		).click(function() {
			var $player = $thing.find('.player');
			if($player.is(':hidden')) {
				var html = recreate();
				html += '<div><a href="javascript:;" class="turnup" title="收起"></a><a href="javascript:;" class="reload" title="重载"></a></div>';
				$player.hide().html(html).fadeIn();
			} else {
				var _this = $(this);
				$player.animate({height:0, width:0}, 'normal', 'swing', function() {
					$(this).css({'height':'', 'width':''}).empty().hide();
					_this.parent().slideDown();
				});
			}
			
			$player.find('.turnup').die().live('click', function() {
				$thing.find('.music img').click();
			});
			
			$player.find('.reload').die().live('click', function() {
				$player.children().eq(0).fadeOut(function() {
					$(this).remove();
					$player.prepend(recreate());
				})
			});
		});
	},
	
	attachPhoto : function(thing_id) {
		var $thing = this.getThingObj(thing_id);
		$thing.find('.medium img').hover(function() {
			$(this).stop().animate({'opacity': 0.7});
		}, function() {
			$(this).stop().animate({'opacity': 1});
		});
		$thing.find('.fancybox[rel="group'+thing_id+'"]').fancybox({
			openEffect	: 'none',
			closeEffect	: 'none'
		});
		$thing.find('.medium img').click(function() {
			$thing.find('.fancybox').eq(0).click();
		});
	},
	
	// 获取当前页thing_id的最大值
	getMaxThingId : function() {
		if($('#things .thing').length == 0) {
			return 0;
		}
		return $('#things .thing').first().attr('data-thing-id');
	},
	
	// 获取当前页thing_id的最小值
	getMinThingId : function() {
		if($('#things .thing').length == 0) {
			return 0;
		}
		return $('#things .thing').last().attr('data-thing-id');
	},
	
	// 获取指定thing节点对象
	getThingObj : function(thing_id) {
		return $('.thing[data-thing-id='+thing_id+']');
	},
	
	getThingType : function(thing_id) {
		return this.getThingObj(thing_id).attr('data-thing-type');
	}
};
	
/**
 * Thing评论对象
 */
function ThingEcho(option) {
	
	this.init = function() {
		var template = '\
			<form>\
				<textarea style="width:558px;height:20px;srcoll:none;overflow:hidden;" name="text"></textarea>\
				<input type="hidden" name="thing_id" value="'+this.thing_id+'" />\
				<input type="button" value="回应" />\
			</form>';
		var $echo = this.getEchoObj(this.thing_id);
		$echo.empty().append($(template));
		new ReplyForm({'thing_id':this.thing_id, 'comment_obj':this});
		this.fetchComments(1);
	};
	
	this.fetchComments = function(page) {
		var _this = this;
		var url = SCABISH.host + '/comment/getComments/thing_id/'+this.thing_id;
		url += '/page/'+page+'/npp/'+this.num_per_page;
		$.post(url, function(response) {
			if(SCABISH.isOk(response)) {
				var data = SCABISH.obtain(response);
				var comments = data.comments;
				
				var template = '<ul class="comment" style="margin-top:10px;">';
				for(var i = 0; i < comments.length; i++) {
					template += _this.getTemplate(comments[i]);
				}
				template += '</ul>';
				template += '<div class="page">'+data.paging+'</div>';
				
				_this.getEchoObj(_this.thing_id).fadeOut(function() {
					$(this).find('.comment').remove();
					$(this).find('.page').remove();
					$(this).append(template).show();
				});
				
				$echo_num = $('.thing[data-thing-id='+_this.thing_id+'] .echo-num');
    			$echo_num.text(data.total_num == 0 ? '' : data.total_num);
    			
				_this.attachEvent();
			}
		});
	};
	
	// 评论区域注册交互事件
	this.attachEvent = function() {
		var _this = this;
		$echo = _this.getEchoObj(_this.thing_id);
		$echo.find('.page span a').die().live('click', function() {
			var href = $(this).attr('href');
			var page = href.substr(href.lastIndexOf('/')+1);
			_this.fetchComments(parseInt(page));			
			return false;
		});
		
		$echo.find('.comment li').each(function() {
			var nickname = $(this).attr('data-nickname');
			var comment_id = $(this).attr('data-comment-id');
			$(this).hover(
				function() {
					var user_cache_id = LOGIN.getUserCacheId();
					if(user_cache_id && user_cache_id != $(this).attr('data-user-id')) {// 已登录的并且非本人可以回复
						$(this).find('.reply-echo').show();
					}
					if(user_cache_id == _this.host_user_id ||user_cache_id == $(this).attr('data-user-id')) { // thing主人或回复者可删除
						$(this).find('.reply-delete').show();
					}
				},
				function() {
					$(this).find('.reply-echo, .reply-delete').hide();
				}
			);
			$(this).find('.reply-delete').die().live('click', function() {
				$.dialog({
					content : '确认要删掉吗？',
					lock : true,
					width : 200,
					okValue : '是的',
					cancelValue : '哦不',
					ok : function() {
						_deleteComment(comment_id);
					},
					cancel : function() {}
				});
			});
			
			$(this).find('.reply-echo').die().live('click', function() {
				_replyComment(comment_id, nickname);
			});
		});
		
		// 回复评论
		var _replyComment = function(comment_id, nickname) {
			var $text = $echo.find('form textarea');
			var re = $.trim($text.val());
			if(nickname) {
				re += re ? ' ' : '';
				re += '@' + nickname + ' ';
			}
			$text.val(re).focus();
		};
		
		// 删除评论
		var _deleteComment = function(comment_id) {
			$.post(SCABISH.host+'/comment/delete/comment_id/'+comment_id, function(response) {
				if(SCABISH.isOk(response)) {
					$echo.find('.comment li[data-comment-id="'+comment_id+'"]').slideUp($(this).remove());
					$echo_num = $('.thing[data-thing-id='+_this.thing_id+'] .echo-num');
	    			$echo_num.text($echo_num.text() ? (parseInt($echo_num.text()) == 1 ? '' : (parseInt($echo_num.text()) - 1)) : '');
				} else {
					var code = SCABISH.obtain(response);
					if(code == 'user_not_login') { // 未登录
						LOGIN.show(function() {
							if(LOGIN.success) { // 登录成功
								_deleteComment(thing_id);
							}
						});
					} else if(code == 'user_cannot_access') { // 无操作权限
						$.dialog({
							'content' : '<span style="color:#FF7F24;font-size:14px;">无此操作权限</span>'
						}).time(1000);
					} else { // 其他未知问题
						//SCABISH.error(code)
						//console.log(code)
					}
				}
			});
		};
		
	};
	
	// 获取指定ID评论信息
	this.fetchSingle = function(comment_id) {
		var _this = this;
		$.get(SCABISH.host + '/comment/getComment/comment_id/'+comment_id, function(response) {
			if(SCABISH.isOk(response)) {
				var comment = SCABISH.obtain(response);
				$(_this.getTemplate(comment)).hide().prependTo(_this.getEchoObj(_this.thing_id).find('.comment')).slideDown();
				_this.attachEvent();
			}
		});
	};
	
	// 获取评论模板
	this.getTemplate = function(comment) {
		return '\
		<li data-comment-id="'+comment.comment_id+'" data-user-id="'+comment.user_id+'" data-nickname="'+comment.nickname+'">\
			<a href="/u/'+comment.user_id+'">\
				<img style="float:left;width:30px;" class="avatar" alt="" src="'+comment.avatar+'">\
			</a>\
			<div style="float:left;margin-left:10px;">\
				<span class="remove-comment"></span>\
				<div class="content">\
					<a class="bbl-name-card" href="/u/'+comment.user_id+'" data-uid="'+comment.user_id+'">'+comment.nickname+'</a>\
					'+comment.text+'\
				</div>\
				<div class="footer">\
					<span class="timestamp" timestamp="'+comment.post_date+'">'+comment.post_date+'</span>\
					<span class="reply-echo" href="javascript:;" style="display:none;"></span>\
					<span class="reply-delete" href="javascript:;" style="display:none;"></span>\
				</div>\
			</div>\
			<div style="clear:both;"></div>\
		</li>';
	};
	// 获取指定thing评论节点对象
	this.getEchoObj = function(thing_id) {
		return $('.thing[data-thing-id='+thing_id+'] .echoes');
	};
	
	this.thing_id = option.thing_id;
	this.num_per_page = option.num_per_page;
	this.host_user_id = option.host_user_id;
	this.init();
}

/**
 * 评论表单对象
 */
function ReplyForm(option) {
	var _this = this;
	this.beforePost = function() {
		if(this.processing) return false;
		var $text = this.getFormObj().find('textarea');
		if($.trim($text.val()) == '') {
			$text.val('').focus(); return false;
    	}
		this.processing = true;
		this.getFormObj().find('input[type="button"]').addClass('disabled');
		return true;
	};
	this.afterPost = function() {
		this.processing = false;
		this.getFormObj().find('input[type="button"]').removeClass('disabled');
	};
	this.post = function() {
		if(!this.beforePost()) return;
		var _this = this;
    	var url = SCABISH.host + '/comment/post/thing_id/'+this.thing_id;
    	$.post(url, this.getFormObj().serialize(), function(response){
    		if(SCABISH.isOk(response)) {
    			_this.getFormObj().find('textarea').val('');
    			$echo_num = $('.thing[data-thing-id='+_this.thing_id+'] .echo-num');
    			$echo_num.text($echo_num.text() ? (parseInt($echo_num.text()) + 1) : 1);
    			_this.comment_obj.fetchSingle(SCABISH.obtain(response));
			} else { // 返回失败代码
				var code = SCABISH.obtain(response);
				if(code == 'user_not_login') { // 未登录
					LOGIN.show(function() {
						if(LOGIN.success) { // 登录成功
							_this.processing = false;
							_this.post();
							_this.getFormObj().find('textarea').val('');
						} else { // 被取消登录
							
						}
						
					});
				} else { // 其他未知问题
					//SCABISH.error(code)
				}
			}
    		_this.afterPost();
        });
	};
	this.getFormObj = function() {
		return $('.thing[data-thing-id='+this.thing_id+'] .echoes form');
	};
	
	this.thing_id = option.thing_id;
	this.comment_obj = option.comment_obj;
	this.processing = false; // 是否正在处理
	
	this.getFormObj().find('textarea').autosize();
	this.getFormObj().find('input[type="button"]').die().live('click', function() {
		_this.post();
	});
}


$(function() {
	 
	// 初始化编辑器
	$('#origin').editor({
		width : 580,
		height : 40, 
		photoUploadUrl : SCABISH.host + '/photo/upload',
		sendUrl : SCABISH.host + '/thing/send',
		postSuccess : function() {
			Thing.fetchThings(Thing.getMaxThingId(), 10, true);
		}
	});
	
	// 设置背景图
	$.get(SCABISH.host+'/api/background', function(response) {
		document.body.style.background = '#eee url('+response+') no-repeat fixed top';
	});
	
	// 判断是否到底
	var arrivedAtBottom = function() {
		var gap = Math.abs($(document).scrollTop() + $(window).height() - $(document).height())
		return gap <= 1;
	};
	
	// thing获取完成后须执行方法
	var thingFinish = function(num) {
		if(num == 0) { // 数据探底
			$('#thing_loading').attr('data-loading', 'no').attr('data-dip', '1').text('没有了').die();
		} else {
			$('#thing_loading').attr('data-loading', 'no').text('继续往下↓');
			$('#thing_loading').bind('mouseover', function() {
				Thing.fetchThings(Thing.getMinThingId(), 10, false, thingFinish);
			});
		}
	};
	
	/**
	 * 获取更早之前的thing
	 */
	var loadEarlierThings = function() {
		if($('#thing_loading').attr('data-loading') == 'yes') return; // 正在获取thing，防止反复查询
		if($('#thing_loading').attr('data-dip') == '1') {
			return;
		}
		$('#thing_loading').attr('data-loading', 'yes').addClass('thing-loading-bg').text('加载中...').die();
		Thing.fetchThings(Thing.getMinThingId(), 10, false, thingFinish);
	};
	
	$('#thing_loading').bind('mouseover', function() {
		loadEarlierThings();
	});
	
	// 注册滚动加载事件
	$(window).scroll(function(){
		if(arrivedAtBottom()) {
			loadEarlierThings();
		}
	});
});